//
//  JDMainScreenViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/2/6.
//

import UIKit
import JXSegmentedView
import SwiftyJSON
/// 龙看板
class JDMainScreenViewController: JDBaseViewController {

    var typeBgView: UIView?
    
    var segmentedTitleDataSource = JXSegmentedTitleDataSource()
    var segmentedView = JXSegmentedView()
    lazy var listContainerView: JXSegmentedListContainerView = {
        return JXSegmentedListContainerView(dataSource: self)
    }()
//    var contentScrollView: UIScrollView?
    
    var releaseImgV: UIImageView?
    var releaseButton: UIButton?
    
    var menuView: JDShowAllMenuView?
    var totalNum: Int = 0
    
    var statusBgView: UIView?
    var numberLabel: UILabel?
    var changeStateButton: UIButton?
    var stateIndex: Int = 0
    
    func customHeaderView() {
        self.numberLabel = UILabel()
        self.statusBgView?.addSubview(self.numberLabel!)
        self.numberLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.statusBgView!).offset(26)
            make.height.equalTo(20)
            make.centerY.equalTo(self.statusBgView!)
        })
        self.numberLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
        self.numberLabel?.text = String.init(format: "动态流量 %zd", self.totalNum)
        
        
        self.changeStateButton = UIButton(type: .custom)
        self.statusBgView?.addSubview(self.changeStateButton!)
        self.changeStateButton?.snp.makeConstraints { make in
            make.top.bottom.equalTo(self.statusBgView!)
            make.trailing.equalTo(self.statusBgView!).offset(-24)
        }

        self.changeStateButton?.addTarget(self, action: #selector(changeStateAction), for: .touchUpInside)
        
        self.changeStateButton?.setTitle("状态", for: .normal)
        self.changeStateButton?.setImage(UIImage(named: "arrow_down"), for: .normal)
      // 这里用appendImgV 重新处理一下
        self.changeStateButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.changeStateButton?.setTitleColor(color("#333333"), for: .normal)
        self.changeStateButton?.semanticContentAttribute = .forceRightToLeft
        
    }
    
    @objc func changeStateAction() {
        print("状态")
        let pickerView = SimplePickerView()
        pickerView.modalPresentationStyle = .fullScreen
        pickerView.modalTransitionStyle = .coverVertical
        pickerView.SourceData = ["待审核","上架中","已结束","违规下架"]
        pickerView.confirmActionBlock = { [weak self] index in
            self?.stateIndex = index
            
            NotificationCenter.default.post(name: NSNotification.Name("refreshBoard"), object: nil,userInfo: ["totalNum": self?.totalNum as Any,"stateIndex": self?.stateIndex as Any])
            
//            self?.getNetData(true, index)
            // TODO: 刷新对应看板的数据啊
            print("刷新对应看板的数据:\(index)")
            
        }
        self.showBottomCustomController(viewController: pickerView, screenHeightRation: 0.3)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.removeSeparatorLine()
        self.setupConfig()
        self.setupUIElements()
        self.customHeaderView()
        self.getTotalRegisterCount()
        // Do any additional setup after loading the view.
    }
    
    func setupConfig() {
        
        self.setupNavigationTitle("尨看板")
//        self.customLeftBarButtonItem("xlbLogo", #selector(leftButtonAction), self)
        self.customImageLeftBarButtonItem("xlbLogo", #selector(leftButtonAction), self)
//        self.customRightBarButtonItems(["JDUserCenter","QRCodeShare"], [#selector(userCenter),#selector(moreAction)], self)
    }
    
    func getTotalRegisterCount() {
//        var params = [String: Any]()
        JDNetWorkRequest(.getTotalRegister([:])) { responseStr in

            printLog("获取总注册人数:\(responseStr)")
//            {"msg":"ok","data":{"count":4},"code":0}
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                if let data = JSON(commonModel?.data as Any).dictionary {
                    self.totalNum = data["count"]?.intValue ?? 0
                    printLog("总数:\(self.totalNum)")
                    self.numberLabel?.text = String.init(format: "动态流量 %zd", self.totalNum)

                }
            } else {
                printLog("修改失败")
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
//    let aaa = JDPlayVideoOrPictureViewController()

    @objc func leftButtonAction() {
//        print("左上角的按钮")
//        let popupConfirmView = JDPopupConfirmView()
//        popupConfirmView.titleStr = "确定删除本条龙商圈推送吗？"
//        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(popupConfirmView)
        
//        JDTools.getKeyWindows()?.addSubview(aaa.view)
    }
    
    @objc func userCenter() {
        
        if !JDTools.checkToken() {
            return
        }
        
        print("个人中心")
        let userCenter = JDUserCenterViewController()
        self.hidesBottomBarPushViewController(userCenter)
    }
    
    @objc func moreAction() {
        let QRCodeView = JDDownLoadQRCode()
        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(QRCodeView)
        return;
        print("是更多")
//        self.menuView = JDShowAllMenuView()
//        self.menuView?.selectedCompleted = { idx in
//            printLog("点击了\(idx),展示吧 ")
//            let QRCodeView = JDDownLoadQRCode()
//            JDTools.getKeyWindows()?.rootViewController?.view.addSubview(QRCodeView)
//        }
    }
    
    @objc func releaseAction() {
        print("发布信息")
        if !JDTools.checkToken() {
            return
        }
        let releaseVC = JDReleaseBoardViewController()
        self.hidesBottomBarPushViewController(releaseVC)
        
    }
    
    func setupUIElements() {
        
        self.typeBgView = UIView()
        self.view.addSubview(self.typeBgView!)
        self.typeBgView?.snp.makeConstraints({ make in
            make.left.equalTo(self.view).offset(12)
            make.right.equalTo(self.view).offset(-12)
            make.top.equalTo(self.view).offset(14+statusBarHeight+44)
            make.height.equalTo(52)
        })
        self.typeBgView?.layer.cornerRadius = 26
        self.typeBgView?.clipsToBounds = true
        self.typeBgView?.backgroundColor = .white
        
        let line = UIView()
        self.typeBgView?.addSubview(line)
        line.snp.makeConstraints { make in
            make.right.equalTo(self.typeBgView!).offset(-81)
            make.centerY.equalTo(self.typeBgView!)
            make.size.equalTo(CGSize(width: 1, height: 15))
        }
        line.backgroundColor = UIColor.init(hexString: "#EEEEEE")
        
//        var releaseImgV: UIImageView?
//        var releaseButton: UIButton?
        self.releaseImgV = UIImageView()
        self.typeBgView?.addSubview(self.releaseImgV!)
        self.releaseImgV?.snp.makeConstraints({ make in
            make.centerY.equalTo(self.typeBgView!)
            make.left.equalTo(line.snp.right).offset(15)
            make.size.equalTo(CGSize(width: 13, height: 12))
        })
        self.releaseImgV?.image = UIImage(named: "sendImgV")?.withRenderingMode(.alwaysOriginal)
        
        self.releaseButton = UIButton(type: .custom)
        self.typeBgView?.addSubview(self.releaseButton!)
        self.releaseButton?.snp.makeConstraints({ make in
            make.left.equalTo(self.releaseImgV!.snp.right).offset(5)
//            make.centerY.equalTo(self.typeBgView!)
            make.top.equalTo(self.typeBgView!).offset(5)
            make.bottom.equalTo(self.typeBgView!).offset(-5)
        })
        self.releaseButton?.setTitle("发布", for: .normal)
        self.releaseButton?.setTitleColor(.black, for: .normal)
        self.releaseButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.releaseButton?.addTarget(self, action: #selector(releaseAction), for: .touchUpInside)
        
        //1、初始化JXSegmentedView
        segmentedView.frame = CGRect(x: 0, y: 0, width: screenWidth-82-24, height: 52)
        segmentedView.backgroundColor = UIColor.white
//        segmentedView.layer.cornerRadius = 26;
        segmentedView.clipsToBounds = true
        segmentedView.delegate = self
        segmentedView.dataSource = segmentedTitleDataSource
        
        //2、配置数据源
        //segmentedViewDataSource一定要通过属性强持有！！！！！！！！！
        
        segmentedTitleDataSource.titles = ["商务","租售","招募", "家政", "综合"]
        segmentedTitleDataSource.isTitleColorGradientEnabled = true
        segmentedTitleDataSource.titleSelectedFont = UIFont.systemFont(ofSize: 16, weight: .semibold)
        segmentedTitleDataSource.titleNormalFont = UIFont.systemFont(ofSize: 16, weight: .regular)
        segmentedTitleDataSource.titleNormalColor = UIColor.init(hexString: "#333333")
        segmentedTitleDataSource.titleSelectedColor = UIColor.init(hexString: "#333333")
        
        //3、配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = JXSegmentedViewAutomaticDimension
        indicator.lineStyle = .lengthen
        segmentedView.indicators = [indicator]

        //4、配置JXSegmentedView的属性
        self.typeBgView?.addSubview(segmentedView)
        
        self.statusBgView = UIView()
        self.view.addSubview(self.statusBgView!)
        statusBgView?.backgroundColor = .commonColor()
        statusBgView?.snp.makeConstraints { make in
            make.leading.equalTo(self.view)
            make.trailing.equalTo(self.view)
            make.top.equalTo(self.segmentedView.snp.bottom)
            make.height.equalTo(36+16)
        }

        //5、初始化JXSegmentedListContainerView
        // TODO: 这个地方还需要适配 36+16)
        listContainerView.frame = CGRectMake(0, 14+52+statusBarHeight+44+(36+16), screenWidth, screenHeight-(14+52)-UIDevice().safeAreaInset.bottom-statusBarHeight-44-(36+16))
        self.view.addSubview(listContainerView)

        //6、将listContainerView.scrollView和segmentedView.contentScrollView进行关联
        self.segmentedView.listContainer = listContainerView
        
        self.segmentedView.reloadData()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
}

extension JDMainScreenViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
    }
    func segmentedView(_ segmentedView: JXSegmentedView, didScrollSelectedItemAt index: Int) {
    }
}

extension JDMainScreenViewController: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return segmentedTitleDataSource.dataSource.count
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {

        if index == 0 {
            // 商务
            let businessVC = JDBusinessViewController()
            businessVC.superVC = self
//            businessVC.totalNum = self.totalNum
            print("这是0")
            return businessVC
        } else if index == 1 {
            // 租售
            let rentSaleVC = JDRentSaleViewController()
            rentSaleVC.superVC = self
//            rentSaleVC.totalNum = self.totalNum
            print("这是1")
            return rentSaleVC
        } else if index == 2 {
            // 招募
            let recruitVC = JDRecruitViewController()
            recruitVC.superVC = self
//            recruitVC.totalNum = self.totalNum
            print("这是2")
            return recruitVC
        }else if index == 3 {
            // 家政
            let housekeepingVC = JDHousekeepingViewController()
            housekeepingVC.superVC = self
//            housekeepingVC.totalNum = self.totalNum
            print("这是3")
            return housekeepingVC
        }else {
            // 综合
            let comprehensiveVC = JDComprehensiveViewController()
            comprehensiveVC.superVC = self
//            comprehensiveVC.totalNum = self.totalNum
            print("这是4")
            return comprehensiveVC
        }
    }
}
